package com.tang.thepath;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.tang.thepath.model.RequestModel;
import com.tang.thepath.service.AuthService;
import com.tang.thepath.service.HttpSubscriber;
import com.tang.thepath.util.AppUtil;
import com.tang.thepath.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

public class LoginActivity extends BaseActivity {

    private Button btnLogin;
    private EditText editLoginId;
    private EditText editPassword;
    private SharedPreferences sp;
    private CheckBox ckRemember;
    private TextView tvVersion;


    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION, //定位
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,//SD卡存储
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,                //相机
            Manifest.permission.READ_PHONE_STATE,      //手机设备信息
    };
    private boolean isNeedCheck = true;
    public static final int PERMISSION_REQUESTCODE =  12345;


    @Override
    protected void onResume() {
        super.onResume();
        if(isNeedCheck){
            checkPermissions(needPermissions);
        }
    }


    private void checkPermissions(String... permissions){
        List<String> needRequestPermissionList = findDeniedPermissions(permissions);
        if(null != needRequestPermissionList && needRequestPermissionList.size() > 0){
            ActivityCompat.requestPermissions(this,needRequestPermissionList.toArray(new String[needRequestPermissionList.size()]),PERMISSION_REQUESTCODE);
        }
    }

    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermisssionList = new ArrayList<>();
        for (String perm : permissions){
            if(ContextCompat.checkSelfPermission(this,perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(this,perm)){
                needRequestPermisssionList.add(perm);
            }
        }
        return needRequestPermisssionList;
    }

    private boolean  verifyPermissions(int[] grantResults){
        for(int result : grantResults){
            if(result != PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == PERMISSION_REQUESTCODE){
            if(!verifyPermissions(grantResults)){
                isNeedCheck = false;
                ToastUtil.showShort("授权失败!");
                finish();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.hide();
            //actionBar.setHomeButtonEnabled(false);
            //actionBar.setDisplayHomeAsUpEnabled(false);
        }

        //setTitle("登录");
        sp = getSharedPreferences("login",MODE_PRIVATE);



        btnLogin = (Button) findViewById(R.id.btn_login);

        editLoginId = (EditText) findViewById(R.id.edit_login_id);
        editPassword = (EditText) findViewById(R.id.edit_password);
        ckRemember = (CheckBox) findViewById(R.id.ck_remember);
        tvVersion = (TextView) findViewById(R.id.tv_version);

        if(sp.contains("login_id")){
            editLoginId.setText(sp.getString("login_id",""));
        }
        if(sp.contains("password")){
            editPassword.setText(sp.getString("password",""));
            ckRemember.setChecked(true);
        }

        tvVersion.setText(AppUtil.getAppVersionName(this));

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(Const.NETWORK_MOD == 0){
                    toast("请检查您的网络设置");
                    return;
                }
                final String loginId = editLoginId.getText().toString();
                final String password = editPassword.getText().toString();

                if(loginId.isEmpty()){
                    toast("登录帐号不能为空");
                    return;
                }

                if(password.isEmpty()){
                    toast("密码不能为空");
                    return;
                }
                showLoading("正在登录");
                RequestModel.LoginRequest request = new RequestModel.LoginRequest();
                request.loginId = loginId;
                request.password = password;
                AuthService.login(request).subscribe(new HttpSubscriber<Boolean>() {
                    @Override
                    protected void onSuccess(Boolean aBoolean) {
                        dismisLoading();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString("login_id",loginId);
                        if(ckRemember.isChecked()) {
                            editor.putString("password", password);
                        }
                        editor.apply();

                        toast("登录成功");
                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                        //startActivity(new Intent(LoginActivity.this,AMapLocationActivity.class));
                        LoginActivity.this.finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismisLoading();
                        toast("登录失败");
                    }
                });
            }
        });

    }


}
